# Creare un pagamento
## Introduzione
Per attivare una dilazione o un pagamento è necessario prima inviare una richiesta di dilazione, quindi reindirizzare l'utente al gateway di pagamento con l'identificativo della dilazione ricevuto, passando un URL di ritorno. Il gateway reindirizzerà all'URL inviato per gestire il ritorno del pagamento.
## Inviare una richiesta di pagamento in unica soluzione
L'endpoint chiede l'avviamento del pagamento e ritorna l'identificativo per il reindirizzamento.
### Richiesta Http
```bash
POST https://api.jatapay.it/scrivi_pagamento
```

### Parametri
| Parametro | Richiesto | Tipo |  Descrizione |
| -------------- | -------------- | -------------- |-------------- |
| importo   | Sì |  int  | L'importo del pagamento espresso in centesimi di Euro   |
|  callback_url  | Sì | string   |  Un URL valido per il ritorno del pagamento  |
|  descrizione_prodotto  | Sì | string   |  La descrizione del prodotto  |
|  cliente  | Sì | string   |  L'identificativo di un cliente esistente, oppure `open` per far compilare i dati al cliente sul gateway di pagamento  |
|  payment_method  | No | string   |  Il metodo di pagamento: `card` per il pagamento con carta, `sdd` per SEPA Direct Debit  |
|  note  | No | string   |  Delle note descrittive per il pagamento  |

:::warning
La richiesta deve avere l'header Content-Type: application/json e includere il parametro nel corpo del JSON e l'header Authorization: Bearer token
:::

**shell**

 ```bash
curl "https://api.jatapay.it/scrivi_pagamento" \
  -H "Authorization: Bearer IL_TOKEN_DI_ACCESSO" \
  -H "Content-Type: application/json" \
  -d '{
    "importo": 2000,
    "callback_url": "https://e-commerce.example.com/callback_url",
    "note": "Pagamento per prodotto esempio",
    "cliente": "open",
    "descrizione_prodotto": "Descrizione del prodotto"
  }'
```
**PHP**

 ```PHP
    $dati_pagamento = array(
            'importo' => 2000, //Importo in centesimi di euro
            'callback_url' => 'https://e-commerce.example.com/callback_url',
            'note' => 'Pagamento per prodotto esempio',
            'cliente' => 'open',
            'descrizione_prodotto' => 'Descrizione del prodotto'
          );

    $url = curl_init("https://api.jatapay.it/scrivi_pagamento");
    $authorization = "Authorization: Bearer ".$token;
    curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($url, CURLOPT_POSTFIELDS, json_encode($dati_pagamento));
    curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($url, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen(json_encode($dati_pagamento)),
      $authorization
    ));

    $result = curl_exec($url);

    $api_response = json_decode($result);

    curl_close($url);

```

**Python**

```python
import requests
import json

token = "IL_TUO_TOKEN"
dati_pagamento = {
  "importo": 2000,
  "callback_url": "https://e-commerce.example.com/callback_url",
  "note": "Pagamento per prodotto esempio",
  "cliente": "open",
  "descrizione_prodotto": "Descrizione del prodotto"
}
url = "https://api.jatapay.it/scrivi_pagamento"
headers = {
  "Content-Type": "application/json",
  "Content-Length": str(len(dati_pagamento)),
  "Authorization": "Bearer " + token
}
response = requests.post(url, headers=headers, data=json.dumps(dati_pagamento))
if response.status_code == 200:
  response = response.json()
else:
  print('Error, ' + str(response.status_code))
```

**Node.js**

```javascript
const token = 'IL_TOKEN_DI_ACCESSO';

const body = {
  importo: 2000, // Importo in centesimi di euro
  callback_url: 'https://e-commerce.example.com/callback_url',
  note: 'Pagamento per prodotto esempio',
  cliente: 'open',
  descrizione_prodotto: 'Descrizione del prodotto'
};

const response = await fetch('https://api.jatapay.it/scrivi_pagamento', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
});

console.log(response.status, await response.json());
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	const token = "IL_TOKEN_DI_ACCESSO"

	body := `{
  "importo": 2000,
  "callback_url": "https://e-commerce.example.com/callback_url",
  "note": "Pagamento per prodotto esempio",
  "cliente": "open",
  "descrizione_prodotto": "Descrizione del prodotto"
}`

	req, err := http.NewRequest("POST", "https://api.jatapay.it/scrivi_pagamento", strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(data))
}
```

**.NET**

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        const string token = "IL_TOKEN_DI_ACCESSO";

        var body = """
            {
              "importo": 2000,
              "callback_url": "https://e-commerce.example.com/callback_url",
              "note": "Pagamento per prodotto esempio",
              "cliente": "open",
              "descrizione_prodotto": "Descrizione del prodotto"
            }
            """;

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var content = new StringContent(body, Encoding.UTF8, "application/json");
        var response = await client.PostAsync("https://api.jatapay.it/scrivi_pagamento", content);

        Console.WriteLine((int)response.StatusCode);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String token = "IL_TOKEN_DI_ACCESSO";

        String body = """
                {
                  "importo": 2000,
                  "callback_url": "https://e-commerce.example.com/callback_url",
                  "note": "Pagamento per prodotto esempio",
                  "cliente": "open",
                  "descrizione_prodotto": "Descrizione del prodotto"
                }
                """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.jatapay.it/scrivi_pagamento"))
                .header("Authorization", "Bearer " + token)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}
```

Il comando ritornerà un JSON con questa struttura:

```json
{
    "app": false,
    "id_pagamento": "6aec4e0551c12de06318f594",
    "link_to_pay": false,
    "payment_url": "https://react.jatapay.it/gateway/6aec4e0551c12de06318f594"
}
```

### Risposta

| Campo | Tipo |  Descrizione |
| -------------- | -------------- |-------------- |
| app   | boolean |  Indica se la richiesta arriva da un client applicativo interno (flag riservato)   |
| id_pagamento   | string |  L'identificativo del pagamento appena creato   |
| link_to_pay   | boolean |  Indica se il pagamento è stato creato come link di pagamento condivisibile   |
| payment_url   | string |  L'URL a cui reindirizzare l'utente per completare il pagamento   |

### Reindirizzare l'utente al gateway di pagamento

Una volta creato il pagamento bisogna reindirizzare l'utente all'URL restituito nel campo `payment_url` della risposta:

```bash
https://react.jatapay.it/gateway/ID_DEL_PAGAMENTO
```

L'utente completerà il processo di pagamento e sarà reindirizzato all'url passato in precedenza.

### Gestire il ritorno del pagamento
In qualunque momento sarà possibile recuperare le informazioni sul pagamentoper il controllo dello stato.
```bash
GET https://api.jatapay.it/entity/pagamenti/ID_DEL_PAGAMENTO
```
:::warning
Sostituire ID_DEL_PAGAMENTO con l'id ottenuto in precedenza
:::
**shell**

 ```bash
curl "https://api.jatapay.it/entity/pagamenti/ID_DEL_PAGAMENTO" \
  -H "Authorization: Bearer IL_TOKEN_DI_ACCESSO"
```
**PHP**

 ```PHP
    $urlstring = "https://api.jatapay.it/entity/pagamenti/".$_GET['id_pagamento'];
    $url = curl_init($urlstring);
    $authorization = "Authorization: Bearer ".$token;
    curl_setopt($url, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($url, CURLOPT_HTTPHEADER, array(
      $authorization
    ));

    $result = curl_exec($url);
    curl_close($url);
    $api_response = json_decode($result);

```
**Python**

```python

import requests
import cgi

form = cgi.FieldStorage()

id_pagamento = form.getValue('id_pagamento')
token = 'IL_TUO_TOKEN'
headers = {"Authorization": "Bearer " + token}
url = 'https://api.jatapay.it/entity/pagamenti/' + id_pagamento
response = requests.get(url,headers=headers)
if response.status_code == 200:
  response = response.json()
else:
  print('Error, ' + str(response.status_code))

```
**Node.js**

```javascript
const token = 'IL_TOKEN_DI_ACCESSO';
const idPagamento = 'ID_DEL_PAGAMENTO';

const response = await fetch(`https://api.jatapay.it/entity/pagamenti/${idPagamento}`, {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();
console.log(response.status, data);
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	const token = "IL_TOKEN_DI_ACCESSO"
	idPagamento := "ID_DEL_PAGAMENTO"

	req, err := http.NewRequest("GET", "https://api.jatapay.it/entity/pagamenti/"+idPagamento, nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+token)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(data))
}
```

**.NET**

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        const string token = "IL_TOKEN_DI_ACCESSO";
        const string idPagamento = "ID_DEL_PAGAMENTO";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await client.GetAsync($"https://api.jatapay.it/entity/pagamenti/{idPagamento}");

        Console.WriteLine((int)response.StatusCode);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String token = "IL_TOKEN_DI_ACCESSO";
        String idPagamento = "ID_DEL_PAGAMENTO";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.jatapay.it/entity/pagamenti/" + idPagamento))
                .header("Authorization", "Bearer " + token)
                .GET()
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}
```

Il comando ritornerà un JSON con questa struttura:

```bash
{
  "_id": "65b2885f6d2f219d702a7f6d",
  "callback_url": "https://e-commerce.example.com/callback_url",
  "client": "JataPay",
  "cliente": "open",
  "credit_management": {},
  "data_controllo": "Thu, 25 Jan 2024 16:12:15 GMT",
  "data_fallimento": "",
  "data_inserimento": "Thu, 25 Jan 2024 16:12:15 GMT",
  "data_pagamento": "Thu, 25 Jan 2024 16:12:15 GMT",
  "esercente": "60c5d53a052bf51a1ca1e1b5",
  "importo": 2000, "note": "Pagamento per prodotto esempio",
  "stato": "unpaid",
  "tentativo_pagamento": 1,
  "tipo": "pagamento",
  "user": "60c5d53a052bf51a1ca1e1b5"
}
```

#### Ricevere il webhook

In alternativa al polling puoi ricevere una notifica HTTP `POST` quando lo stato cambia, senza dover interrogare le API.

Il webhook si configura dalla Dashboard nella sezione **[Sviluppatori](https://dashboard.jatapay.it/sviluppatori)** oppure via API con l'endpoint `POST /esercente/developer_options` (vedi [Opzioni sviluppatore](/riferimento-api/opzioni-sviluppatore)).

Ogni notifica è firmata con il `webhook_secret` dell'esercente: vedi [Webhook](/riferimento-api/opzioni-sviluppatore/webhook) per il calcolo e la verifica della firma in tutti i linguaggi.
